package com.houor.data;

import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpHost;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.houor.device.controller.ControllerDataContainer;
import com.houor.device.controller.DataServer;
import com.houor.device.controller.data.SensorReportData;

public class DataReportHandler implements Runnable {

	private static Logger logger = LoggerFactory.getLogger(DataReportHandler.class);

	// specify the host, protocol, and port
	DefaultHttpClient httpclient = new DefaultHttpClient();
	HttpHost target = new HttpHost("210.43.35.190", 8080, "http");
	String url = "/iAgriculture/agri/data/reportData";

	@Override
	public void run() {
		logger.debug("Start data report handler...");

		while (DataServer.flag) {

			try {

				SensorReportData data = ControllerDataContainer.reportDataQueur.poll();
				if (data == null) {
					Thread.sleep(3000);
					continue;
				}

				StringBuffer sb = new StringBuffer();
				sb.append(url).append("?").append("deviceId=").append(data.getDeviceId()).append("&sensorAddress=").append(data.getSensorType()).append("&value=").append(data.getValue());
				logger.debug("url : {}", sb.toString());

				// specify the get request
				HttpGet getRequest = new HttpGet(sb.toString());

				HttpResponse httpResponse = httpclient.execute(target, getRequest);
				HttpEntity entity = httpResponse.getEntity();

				logger.debug(httpResponse.getStatusLine().toString());

				Header[] headers = httpResponse.getAllHeaders();
				for (int i = 0; i < headers.length; i++) {
					logger.debug(headers[i].toString());
				}

				if (entity != null) {
					logger.debug(EntityUtils.toString(entity));
				}

			} catch (Exception e) {
				e.printStackTrace();
			}
		}

		logger.debug("Stop data report handler...");
		httpclient.getConnectionManager().shutdown();

	}

}
